package com.shangxia.dog.config.security;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhouya24
 * @date 2021/11/18 15:26
 * @apiNote 登录加密JwtTokenUtil
 */

@Slf4j
@Component
public class JwtTokenUtil {

    private static final String CLAIM_KEY_USERNAME = "sub";
    private static final String CLAIM_KEY_CREATED = "CREATED";

    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.expiration}")
    private Long expiration;


    /**
     * @param token       token
     * @param userDetails userDetails
     * @return token是否失效
     */
    public boolean validateToken(String token, UserDetails userDetails) {
        String userName = getUserNameFromToken(token);
        return !StringUtils.isEmpty(userName)
                && userName.equals(userDetails.getUsername())
                && new Date().before(getClaimsFromToken(token).getExpiration());
    }

    /**
     * @param token token
     * @return 是否可以刷新token
     */
    public boolean canRefreshToken(String token) {
        return new Date().before(getClaimsFromToken(token).getExpiration());
    }

    /**
     * @param token token
     * @return 刷新token
     */
    public String refreshToken(String token) {
        if (!canRefreshToken(token)) {
            throw new RuntimeException("token已失效，不可以刷新！");
        }
        Claims claims = getClaimsFromToken(token);
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claims);
    }


    /**
     * 根据用户信息生成token
     *
     * @param userDetails 用户信息
     * @return token
     */
    public String generateToken(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claims);
    }

    /**
     * @param token token
     * @return 用户名
     */
    public String getUserNameFromToken(String token) {
        return getClaimsFromToken(token).getSubject();
    }

    /**
     * @param token token
     * @return 荷载
     */
    private Claims getClaimsFromToken(String token) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }


    /**
     * 根据 荷载 生成 JWT token
     *
     * @param claims 荷载
     * @return JWT token
     */
    private String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

}
